﻿using System;
using System.Threading;

namespace PanoramicData.TickTockBlink
{
	public static class TickTockBlinkProgram
	{
		/// <summary>
		/// Console access point
		/// </summary>
		private static void Main()
		{
			var tokenSource = new CancellationTokenSource();

			Console.CancelKeyPress += delegate
			{
				Console.WriteLine("Ctrl-C pressed");
				tokenSource.Cancel();
			};


			// Will never exit until Ctrl-C is pressed
			MainLoop(tokenSource.Token);
		}

		public static void MainLoop(CancellationToken cancellationToken)
		{
			while (!cancellationToken.IsCancellationRequested)
			{
				var blink1 = new Blink1.Blink1();

				// Connect to device
				blink1.Open();
				var dateTime = DateTime.Now;
				var color = TimeColorHelper.GetColor(dateTime);

#if(DEBUG)
				// Flicker when in debug
				blink1.SetRgb(0, 0, 0);
				Thread.Sleep(10);
#endif

				// Flash black if on the hour or quarter hour
				switch (TimeColorHelper.GetFlashType(dateTime))
				{
					case FlashType.Single:
						blink1.SetRgb(0, 0, 0);
						Thread.Sleep(250);
						break;
					case FlashType.Double:
						blink1.SetRgb(0, 0, 0);
						Thread.Sleep(250);
						blink1.SetRgb(color.R, color.G, color.B);
						Thread.Sleep(250);
						blink1.SetRgb(0, 0, 0);
						Thread.Sleep(250);
						break;
				}

				// Set correct color
				blink1.SetRgb(color.R, color.G, color.B);

				// Close the connection
				blink1.Close();

				Thread.Sleep(700);
			}
		}
	}
}